package com.qiku.service.impl;

import com.qiku.dao.RoleMapper;
import com.qiku.domain.Role;
import com.qiku.domain.RoleMenuVo;
import com.qiku.domain.RoleVo;
import com.qiku.domain.Role_menu_relation;
import com.qiku.service.RoleService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 角色列表查询&条件查询
     *
     * @param roleVo
     * @return
     */
    @Override
    public List<Role> findAllRole(RoleVo roleVo) throws InvocationTargetException, IllegalAccessException {
        Role role = new Role();
        //对象属性拷贝
        BeanUtils.copyProperties(role, roleVo);
        return roleMapper.findAllRole(role);
    }

    /**
     * 添加角色信息
     *
     * @param role
     * @return
     */
    @Override
    public int saveRole(Role role) {
        Date date = new Date();
        role.setCreatedTime(date);
        role.setUpdatedTime(date);
        role.setCreatedBy("system");
        role.setUpdatedBy("system");
        return roleMapper.saveRole(role);
    }

    /**
     * 修改角色信息
     *
     * @param role
     * @return
     */
    @Override
    public int updateRole(Role role) {
        Date date = new Date();
        role.setUpdatedTime(date);
        return roleMapper.updateRole(role);
    }

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    @Override
    public void deleteRole(Integer id) {
        //根据角色外键 清空中间表
        roleMapper.deleteRoleContextMenu(id);
        roleMapper.deleteRole(id);
    }

    @Override
    public List<Integer> findMenuByRoleId(Integer roleId) {
        return roleMapper.findMenuByRoleId(roleId);
    }

    @Override
    public void RoleContextMenu(RoleMenuVo roleMenuVo) {
        //根据角色外键 清空中间表
        roleMapper.deleteRoleContextMenu(roleMenuVo.getRoleId());
        for (Integer menuId : roleMenuVo.getMenuIdList()) {
            Date date = new Date();
            Role_menu_relation rm = new Role_menu_relation();
            rm.setRoleId(roleMenuVo.getRoleId());
            rm.setMenuId(menuId);
            rm.setCreatedTime(date);
            rm.setUpdatedTime(date);
            rm.setCreatedBy("system");
            rm.setUpdatedby("system");
            roleMapper.RoleContextMenu(rm);
        }
    }
}
